package handler

import (
	"article-cms/cache"
	"article-cms/model"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	redis_key := "login_error_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	var user model.User
	err := model.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != password {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次,封禁两小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code":     200,
		"msg":      "登录成功",
		"username": username,
		"password": password,
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultPostForm("size", "3"))
	offset := (page - 1) * size
	var users []model.User
	redis_key := "list_page_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.
			Offset(offset).
			Limit(size).
			Debug().
			Find(&users)
		jsonData, _ := json.Marshal(users)
		cache.Rdb.Set(cache.Ctx, redis_key, string(jsonData), time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &users)
	}

	var total int64
	model.DB.Model(&model.User{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  users,
		"total": total,
	})
}
